package com.cqsw.config;


import com.cqsw.filter.LoginFilter;
import com.cqsw.service.impl.MyUserDetailsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname SecurityConfig
 * @Description TODO
 * @Date 2022/6/13 14:35
 * @Created by Smith.Liu
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final MyUserDetailsService myUserDetailsService;

    @Autowired
    public SecurityConfig(MyUserDetailsService myUserDetailsService) {
        this.myUserDetailsService = myUserDetailsService;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setFilterProcessesUrl("/doLogin");
        loginFilter.setUsernameParameter("name");
        loginFilter.setPasswordParameter("password");
        loginFilter.setValidateCodeParameter("validateCode");
        loginFilter.setAuthenticationManager(authenticationManager());
        loginFilter.setAuthenticationSuccessHandler((res, resp, auth) -> {
            Map<String, Object> result = new HashMap();
            result.put("msg", "登录成功");
            result.put("code", 200);
            result.put("用户信息", auth.getPrincipal());
            resp.setContentType("application/json; charset=UTF-8");
            resp.setStatus(HttpStatus.OK.value());
            String s = new ObjectMapper().writeValueAsString(result);
            resp.getWriter().println(s);
        });
        loginFilter.setAuthenticationFailureHandler((res, resp, ex) -> {
            Map<String, Object> result = new HashMap();
            result.put("msg", "登录失败" + ex.getMessage());
            result.put("code", 401);
            resp.setContentType("application/json; charset=UTF-8");
            resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            String s = new ObjectMapper().writeValueAsString(result);
            resp.getWriter().println(s);
        });

        return loginFilter;
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/validateCode", "/hello").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .cors()
                .configurationSource(configurationSource())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((res, resp, ex) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                    resp.getWriter().println("无权访问，请认证！");
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((res, resp, auth) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    resp.getWriter().println("注销成功");
                })
                .and().csrf().disable()
        ;
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
        corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

}
